﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Pharmacy.Data.Entity;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Objects;
using Pharmacy.Ultilities.Configurations;
using System.Data.Common;

namespace Pharmacy.Data
{
    public static class ObjectContextFactory
    {
        #region Declarations
        private const string DEFAULT_CONNECTION_PROVIDER = "System.Data.SqlClient";
        #endregion

        public static IObjectContext CreatePharmacyContext(string UserName = "Unknow", string connectionString = null)
        {
            ObjectContext context = null;
            context = connectionString == null ?
                new ObjectContext("name=PharmacyContext") :
                new ObjectContext(BuildConnectionForPharmcay(connectionString));
            context.DefaultContainerName = "PharmacyContext";
            context.ContextOptions.LazyLoadingEnabled = true;

            ObjectContextSql createObject =  new ObjectContextSql(context);
            createObject.UserName = UserName;
            //Manual Open Connection
            //http://msdn.microsoft.com/en-us/library/bb896325.aspx
            context.Connection.Open();

            return createObject;
        }

        private static string BuildConnectionForPharmcay(string strCnn)
        {
            EntityConnectionStringBuilder cnnBuilder = new EntityConnectionStringBuilder();
            cnnBuilder.Provider = DEFAULT_CONNECTION_PROVIDER;
            cnnBuilder.ProviderConnectionString = strCnn;
            cnnBuilder.Metadata = @"res://Pharmacy.Data.Entity/Pharmacy.csdl|res://Pharmacy.Data.Entity/Pharmacy.ssdl|res://Pharmacy.Data.Entity/Pharmacy.msl";            
            return cnnBuilder.ToString();
        }

        public static bool TestConnection(string connectionString)
        {
            string provider = DEFAULT_CONNECTION_PROVIDER;
            DbConnection cn = DbProviderFactories.GetFactory(provider).CreateConnection();
            cn.ConnectionString = connectionString;
            //If the Database in Coonection is empty, connection is still openned. So check if the Database is null
            if (cn.Database.Trim() == string.Empty)
                return false;
            try
            {
                cn.Open();
            }
            catch
            {
                return false;
            }
            finally
            {
                if (cn.State != System.Data.ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
            return true;
        }
    } 
}
